﻿using SSC.Models;
using SSC.Services;
using SSC;
using System.Windows.Threading;

public class AlarmMonitor
{
    private readonly List<FaultDefinition> _definitions;
    private readonly AlarmLogService _logService;
    private DispatcherTimer _timer;

    public AlarmMonitor()
    {
        _definitions = LoadAlarmDefinitions();
        _logService = new AlarmLogService();
    }

    public void Start()
    {
        _timer = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(3)
        };
        _timer.Tick += Timer_Tick;
        _timer.Start();
    }

    public void Stop()
    {
        if (_timer != null)
        {
            _timer.Stop();
            _timer.Tick -= Timer_Tick;
        }
    }

    private async void Timer_Tick(object? sender, EventArgs e)
    {
        var activeAlarms = _logService.GetActiveAlarms(); // 统一获取当前内存中所有报警
        var activeAddresses = new HashSet<string>(activeAlarms.Select(a => a.AlarmAddress));

        foreach (var def in _definitions)
        {
            bool isActive = await Variable.PlcConnection.ReadBool(def.AlarmAddress);

            if (isActive && !activeAddresses.Contains(def.AlarmAddress))
            {
                _logService.StartAlarm(def.AlarmAddress, def.AlarmMessage);
            }
            else if (!isActive && activeAddresses.Contains(def.AlarmAddress))
            {
                _logService.EndAlarm(def.AlarmAddress);
            }
        }
    }

    private List<FaultDefinition> LoadAlarmDefinitions()
    {
        string query = "SELECT * FROM tbAlarmDefinitions";
        return App.DatabaseService.GetAll<FaultDefinition>(query);
    }
}
